﻿using System.IO;
using System.Xml;
using System.Runtime.Serialization;
using Orchard.Environment.Extensions;

namespace FruitCake.SupportLibrary
{
    [OrchardFeature("FruitCake.SupportLibrary.Helpers")]
    public static class Helper
    {
        public static string XmlSerialize<T>(T obj)
        {
            string serialization;

            using (var sw = new StringWriter())
            {
                using (var writer = new XmlTextWriter(sw))
                {
                    var serializer = new DataContractSerializer(obj.GetType());
                    serializer.WriteObject(writer, obj);
                    writer.Flush();
                    serialization = sw.ToString();
                }
            }

            return serialization;
        }

        public static T XmlDeserialize<T>(string serialization)
        {
            var serializer = new DataContractSerializer(typeof(T));
            var doc = new XmlDocument();
            doc.LoadXml(serialization);
            var reader = new XmlNodeReader(doc.DocumentElement);
            return (T)serializer.ReadObject(reader);
        }
    }
}